// app.js
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./config/swagger');
const todoRoutes = require('./routes/todoRoutes');

const app = express();

// 中间件
app.use(express.json());

// Swagger文档路由 (作为View层)
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

// API路由
app.use('/todos', todoRoutes);

// 根路由重定向到API文档
app.get('/', (req, res) => {
  res.redirect('/api-docs');
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    error: '服务器内部错误',
    message: err.message
  });
});

module.exports = app;